﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using AutoOm.Manage.Model;
using AutoOm.Manage.Om.OmTask;

namespace AutoOm.Manage.Om
{
    public class ProjectProcess
    {
        public List<ITask> Tasks;

        public ProjectProcess(Project project)
        {
            Tasks = new List<ITask>();
            foreach (var projectTask in project.Tasks)
            {
                var task = GetTaskType(project.ProjectConfig, projectTask.TaskType);
                task.RegisterProcess(result =>
                {
                    RecordLog(projectTask.ProjectTaskLog, result);
                });
                Tasks.Add(task);
            }
        }

        private void RecordLog(ProjectTaskLog log, string result)
        {
            Debug.WriteLine(result);
            log.Log += result;
        }

        private ITask GetTaskType(ProjectConfig config, string taskName)
        {
            var type = Type.GetType($"AutoOm.Manage.Om.OmTask.{taskName}Task");
            if (type == null)
            {
                throw new Exception("type is null");
            }
            var instance = Activator.CreateInstance(type, config) as ITask;
            return instance;
        }
    }
}